import os
import sys
import chardet
import shutil
from PyQt5 import  QtWidgets
from PyQt5.QtWidgets import (QApplication, QMainWindow, QFileDialog, 
                             QMessageBox, QVBoxLayout, QPushButton, 
                             QTextEdit, QLabel, QWidget, QListWidget)
from PyQt5.QtCore import Qt, QUrl
from PyQt5.QtGui import QIcon,QDragEnterEvent, QDropEvent
from utils import resource_path
image_path = resource_path("img/")


class EncodingConverter(QMainWindow):
    def __init__(self):
        super().__init__()
        self.initUI()
        self.file_list = []
        # 启用拖拽功能
        self.setAcceptDrops(True)
    
    # 添加拖拽事件处理
    def dragEnterEvent(self, event):
        # 检查拖入的是否是文件
        if event.mimeData().hasUrls():
            event.acceptProposedAction()
        else:
            event.ignore()
    
    def dropEvent(self, event):
        # 获取拖入的文件路径
        urls = event.mimeData().urls()
        file_paths = [url.toLocalFile() for url in urls if url.isLocalFile()]
        
        # 过滤只保留.c和.h文件
        valid_files = [f for f in file_paths if f.lower().endswith(('.c', '.h'))]
        
        if valid_files:
            self.file_list.extend(valid_files)
            self.list_files.clear()
            self.list_files.addItems([os.path.basename(f) for f in self.file_list])
            self.btn_convert.setEnabled(True)
            self.txt_log.append(f"通过拖拽添加了 {len(valid_files)} 个文件")
        else:
            self.txt_log.append("拖入的文件不是.c或.h格式")


class GB2312Converter:
    def __init__(self):
        super().__init__()

    def detect_encoding(self,file_path):
        with open(file_path, 'rb') as f:
            raw_data = f.read(1000)  # 读取前1000个字节检测编码
            result = chardet.detect(raw_data)
            return result['encoding']

    def convert_gb2312_to_utf8(self,input_file, output_file):
        try:
            # 检测文件编码
            encoding = self.detect_encoding(input_file)

            # 读取文件内容
            with open(input_file, 'r', encoding=encoding, errors='replace') as f:
                content = f.read()

            # 确保输出目录存在
            os.makedirs(os.path.dirname(output_file), exist_ok=True)

            # 写入UTF-8格式
            with open(output_file, 'w', encoding='utf-8', errors='replace') as f:
                f.write(content)

            return True
        except Exception as e:
            return str(e)

class EncodingConverter(QMainWindow):
    def __init__(self):
        super().__init__()
        self.initUI()
        self.file_list = []
        self.setAcceptDrops(True)
        self.converter = GB2312Converter()
    
    def initUI(self):
        self.setWindowTitle('GB2312转UTF-8 转换工具 V1.0.0')
        self.setWindowIcon(QIcon(image_path+'favicon.ico'))  # 设置窗口图标
        screen_size = QtWidgets.QDesktopWidget().screenGeometry()
        P_screen_w = int(0.25*screen_size.width())
        P_screen_h = int(0.5*screen_size.height())
        self.resize(P_screen_w, P_screen_h)
        
        # 创建主部件
        main_widget = QWidget()
        self.setCentralWidget(main_widget)
        
        layout = QVBoxLayout()
        
       # 文件选择按钮
        self.btn_select = QPushButton('选择文件(.c/.h)', self)
        self.btn_select.clicked.connect(self.select_files)
        layout.addWidget(self.btn_select)
        
        # 文件列表显示
        self.lbl_selected = QLabel('已选择文件:', self)
        layout.addWidget(self.lbl_selected)
        
        self.list_files = QListWidget(self)
        self.list_files.setAcceptDrops(False)  # 列表本身不接受拖拽
        layout.addWidget(self.list_files)
        
        # 转换按钮
        self.btn_convert = QPushButton('批量转换为UTF-8', self)
        self.btn_convert.clicked.connect(self.convert_files)
        self.btn_convert.setEnabled(False)
        layout.addWidget(self.btn_convert)
        
        # 日志显示
        self.txt_log = QTextEdit(self)
        self.txt_log.setReadOnly(True)
        self.txt_log.setPlaceholderText("将.c/.h文件拖拽到此处或使用上方按钮选择文件...")
        layout.addWidget(self.txt_log)
        
        main_widget.setLayout(layout)
        self.statusBar().showMessage('就绪')
    
    def dragEnterEvent(self, event):
        if event.mimeData().hasUrls():
            event.acceptProposedAction()
        else:
            event.ignore()
    
    def dropEvent(self, event):
        urls = event.mimeData().urls()
        file_paths = [url.toLocalFile() for url in urls if url.isLocalFile()]
        valid_files = [f for f in file_paths if f.lower().endswith(('.c', '.h'))]
        
        if valid_files:
            self.file_list.extend(valid_files)
            self.list_files.clear()
            self.list_files.addItems([os.path.basename(f) for f in self.file_list])
            self.btn_convert.setEnabled(True)
            self.txt_log.append(f"添加了 {len(valid_files)} 个文件")
        else:
            self.txt_log.append("警告: 拖入的文件不是.c或.h格式")
    
    def select_files(self):
        options = QFileDialog.Options()
        files, _ = QFileDialog.getOpenFileNames(
            self, "选择C/C++文件", "", 
            "C/C++ Files (*.c *.h);;All Files (*)", 
            options=options)
        
        if files:
            self.file_list = files
            self.list_files.clear()
            self.list_files.addItems([os.path.basename(f) for f in files])
            self.btn_convert.setEnabled(True)
            self.txt_log.append(f"已选择 {len(files)} 个文件")
    
    def convert_files(self):
        if not self.file_list:
            return
            
        output_dir = os.path.join(os.getcwd(), 'output')
        if not os.path.exists(output_dir):
            os.makedirs(output_dir)
            self.txt_log.append(f"已创建输出目录: {output_dir}")
        
        success_count = 0
        fail_count = 0
        
        for input_file in self.file_list:
            try:
                file_name = os.path.basename(input_file)
                output_file = os.path.join(output_dir, file_name)
                
                result = self.converter.convert_gb2312_to_utf8(input_file, output_file)
                if result is True:
                    self.txt_log.append(f"转换成功: {file_name}")
                    success_count += 1
                else:
                    self.txt_log.append(f"转换失败 {file_name}: {result}")
                    fail_count += 1
            except Exception as e:
                self.txt_log.append(f"转换失败 {file_name}: {str(e)}")
                fail_count += 1
        
        msg = f"转换完成! 成功: {success_count}, 失败: {fail_count}"
        self.txt_log.append(msg)
        QMessageBox.information(self, '完成', msg)
        
        self.file_list = []
        self.list_files.clear()
        self.btn_convert.setEnabled(False)

def main():
    app = QApplication(sys.argv)
    ex = EncodingConverter()
    ex.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()